# 学生姓名：张仁杰
# 开放时间：2021/4/10 11:49

from IPy import IP
import os


def run_ip(ips):
    if len(ips) > 1:
        print("这是一个网段")
        print('网段', ips.net())
        print("子网掩码", ips.netmask())
        for i in ips:
            path = f'C:\Windows\System32\ping {i} -n 1 -w 1'
            ret = os.system(path)
            if ret == 0:
                with open('IP地址ping成功.txt', 'a+', encoding='utf-8') as f:
                    f.write(f'{i} 已被使用\n')
            else:
                with open('IP地址ping失败.txt', 'a+', encoding='utf-8') as f:
                    f.write(f'{i} 未被使用\n')
    else:
        print("这是一个IP地址")
        path = f'C:\Windows\System32\ping {ips} -n 1 -w 1'
        ret = os.system(path)
        if ret == 0:
            with open('IP地址ping成功.txt', 'a+', encoding='utf-8') as f:
                f.write(f'{ips} 已被使用\n')
        else:
            with open('IP地址ping失败.txt', 'a+', encoding='utf-8') as f:
                f.write(f'{ips} 未被使用\n')


ip = input("请输入ip地址或网段：")
# IP方法可以检测IP网段的合法性
# from IPy import IP
# try:
#     IP(input())
#     print(True)
# except Exception:
#     print(False)

# 方法二 不调用模块
words = ip.split('.')
if len(words) != 4:
    try:
        raise ValueError("你输入的ip格式错误")
    except ValueError as e:
        print(e)
else:
    for i in range(4):
        if i != 3:
            try:
                word = int(words[i])
            except ValueError:
                print("IP地址只能包含整数型字符")
                break
            if int(words[i]) < 0 or int(words[i]) > 255:
                try:
                    raise ValueError("IP地址有效范围是[0-255]之间的整型")
                except ValueError as e:
                    print(e)
                    break
        else:
            if '/' in words[i]:
                ips = words[i].split('/')
                if ips[0] != '0' and ips[1] != '24':
                    try:
                        raise ValueError("你输入的ip网段格式错误")
                    except ValueError as e:
                        print(e)
                        break
            else:
                if int(words[i]) < 0 or int(words[i]) > 255:
                    try:
                        raise ValueError("IP地址有效范围是[0-255]之间的整型")
                    except ValueError as e:
                        print(e)
                        break
    else:
        ips = IP(ip)
        run_ip(ips)
